var express = require('express');
var router = express.Router();
const dao = require('../dao/index.js');
const Cache = require('../utils/cache')

/* 用户列表. */
router.get('/list', async function(req, res, next) {
	
	let pageSize = req.query.pageSize ?? 10;
	let pageNum = req.query.pageNum ?? 1;
	
	let sql1 = `select u.id, u.name, u.is_admin, u.is_lock from t_user u where u.deleted=0 `
	let sql2 = `select count(u.id) as total from t_user u where u.deleted=0 `
	
	let type = req.query.type ?? undefined
	
	if(type) {
		sql1 += `and u.is_admin = ${type} `
		sql2 += `and u.is_admin = ${type} `
	}
	
	sql1 += `limit ${pageSize*(pageNum-1)}, ${pageSize}`
	
	try {
		let result1 = await dao.query(sql1)
		let result2 = await dao.query(sql2)
		
		res.send({
			code: 0,
			msg: '查询成功',
			result: result1,
			total: result2[0].total
		})
	} catch(e) {
		res.send(e.toString())
	}
});

/* 新建用户 */
router.post('/create', function(req, res, next) {
	let token = req.header('x-token')
	let body = req.body;
	let loginuser = Cache.get(token)
	
	if(loginuser.is_admin == 0) {
		res.send({
			'code': 100004,
			'msg': '非管理员无权执行该操作'
		})
		return;
	}
	
	let sql = `INSERT INTO t_user VALUES (null, '${body.name}', '${body.password}', '${body.type}', 0, 0)`
	dao.query(sql).then(result=>{
		res.send({
			'code': 0,
			'msg': '插入成功',
			'result': result
		})
	}).catch(e=>{
		res.send(e.toString())
	})
});

module.exports = router;
